<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="searchForm.idNumber" placeholder="请输入身份证号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.activeStatus" placeholder="请选择状态" clearable>
            <el-option label="有效" :value="true" />
            <el-option label="无效" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'patient:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增患者
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="patientId"
        stripe
      >
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="idNumber" label="身份证号" min-width="180" />
        <el-table-column label="年龄" width="80">
          <template #default="scope">
            <span>{{ calculateAge(scope.row.birthDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.contactInfo?.phone }}</span>
          </template>
        </el-table-column>
        <el-table-column label="地址" min-width="200">
          <template #default="scope">
            <span>{{ scope.row.contactInfo?.address || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登记日期" min-width="180">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.registrationDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="activeStatus" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.activeStatus ? 'success' : 'danger'">
              {{ scope.row.activeStatus ? '有效' : '无效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'patient:read'"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'patient:update'"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleDelete(scope.row)"
              v-permission="'patient:delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { patientAPI } from '@/utils/api'
import { formatDateTime } from '@/utils/date'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  name: '',
  idNumber: '',
  phone: '',
  activeStatus: null
})

// 计算年龄
const calculateAge = (birthDate) => {
  if (!birthDate) return '--'
  const today = new Date()
  const birth = new Date(birthDate)
  let age = today.getFullYear() - birth.getFullYear()
  const monthDiff = today.getMonth() - birth.getMonth()
  
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--
  }
  
  return age
}

// 获取患者列表
const getPatients = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    // 特殊处理联系方式
    if (params.phone) {
      params['contactInfo.phone'] = params.phone
      delete params.phone
    }
    
    const res = await patientAPI.getPatients(params)
    
    // 修复这里 - 使用正确的数据字段名称
    if (res.success && res.data) {
      // 使用patients而不是items
      tableData.value = res.data.patients || []
      total.value = res.data.total || 0
      
      // 调试输出
      console.log('获取到患者数据:', tableData.value.length, '条记录')
    } else {
      console.error('后端返回格式异常:', res)
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取患者列表失败', error)
    ElMessage.error('获取患者列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getPatients()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  currentPage.value = 1
  getPatients()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getPatients()
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getPatients()
}

// 新增患者
const handleCreate = () => {
  router.push('/patients/create')
}

// 查看患者详情
const handleView = (row) => {
  router.push(`/patients/detail/${row.patientId}`)
}

// 编辑患者
const handleEdit = (row) => {
  router.push(`/patients/edit/${row.patientId}`)
}

// 删除患者
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除患者 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await patientAPI.deletePatient(row.patientId)
      ElMessage.success('删除成功')
      getPatients()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 页面加载时获取数据
onMounted(() => {
  getPatients()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-container .el-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .filter-container .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style> 


